import { createStore } from 'vuex'
import { getInfoApi, loginApi, logoutApi } from '@/api/manager'
import { removeToken, setToken } from '@/utils/auth'

// 创建一个新的 store 实例
// store只针对数据，跳转不需要store进行
const store = createStore({
  state() {
    return {
      // 用户信息
      user: {},
      // 侧边宽度
      asideWidth: '250px',
      menus: [],
      ruleName: [],
    }
  },
  mutations: {
    // 记录用户信息
    SET_USERINFO(state, user) {
      state.user = user
    },
    // 展开、缩起侧边
    SET_ASIDEWIDTH(state) {
      state.asideWidth = state.asideWidth === '250px' ? '48px' : '250px'
    },
    SET_MENUS(state, menus) {
      state.menus = menus
    },
    SET_RULENAME(state, ruleName) {
      state.ruleName = ruleName
    },
  },
  actions: {
    loginAction({ commit }, { username, password }) {
      return new Promise((resolve, reject) => {
        loginApi(username, password)
          .then((res) => {
            if (res) {
              const token = res.token
              setToken(token)
              resolve(res)
            }
          })
          .catch((err) => reject(err))
      })
    },
    getinfoAction({ commit }) {
      return new Promise((resolve, reject) => {
        getInfoApi()
          .then((res) => {
            commit('SET_USERINFO', res)
            commit('SET_MENUS', res.menus)
            commit('SET_RULENAME', res.ruleNames)
            resolve(res)
          })
          .catch((err) => reject(err))
      })
    },
    logoutAction({ commit }) {
      // action中有网络请求的都需要包裹 Promise，因为action本事返回的就是 promise
      return new Promise((resolve, reject) => {
        logoutApi()
          .then((res) => {
            removeToken()
            commit('SET_USERINFO', {})
            resolve(res)
          })
          .catch((err) => reject(err))
      })
    },
  },
})

export default store
